﻿(function () {
    'use strict';
    var skillsController = function ($scope, $log, $routeParams, skillsFactory, skillTypeSkills) {
        $scope.skillTypes = skillTypeSkills.skillTypes;
        $scope.skills = skillTypeSkills.skills; //getSkills(skillTypeSkills.skills);
        $scope.skillType = getSkillType(skillTypeSkills.skillTypeId);
        $scope.isNewMode = false;
        $scope.editedSkill = {};
        
        function clearNewMode() {
            $scope.isNewMode = false;
            $scope.newSkill = "";
        }

        function clearEditMode() {
            $scope.isEditMode = false;
            $scope.newSkill = "";
        }

        $scope.skillTypeChange = function () {
            clearNewMode();
            skillsFactory.getSkills($scope.skillType.id)
                .then(function (skills) {
                    $scope.skills = skills; //getSkills(skills);
                }, function (response) {
                    console.log(response);
                });

        };

        $scope.addSkill = function () {
            $scope.isNewMode = true;
        };

        $scope.edit = function (skill) {
            $scope.editedSkill = skill;
            $scope.isEditMode = true;
            $scope.newSkill = skill.name;
        };

        $scope.updateSkill = function () {
            $scope.editedSkill.name = $scope.newSkill;
            skillsFactory.updateSkill($scope.editedSkill)
                .then(function (response) {
                    console.log(response);
                    clearEditMode();
                }, function (response) {
                    console.log(response);
                });
        };

        $scope.saveNewSkill = function () {
            var newSkill = {
                Name: $scope.newSkill,
                SkillTypeId: $scope.skillType.id
            };
            skillsFactory.addSkill(newSkill)
            .then(function (response) {
                console.log(response);
                $scope.skills.push(response);
                $scope.newSkill = '';
            }, function (response) {
                console.log(response);
            });
            clearNewMode();
        };

        $scope.cancelNewSkill = function () {
            clearNewMode();
        };

        $scope.cancelUpdate = function () {
            clearEditMode();
        };

        function getSkillType(skillTypeId) {
            for (var i = 0; i < $scope.skillTypes.length; i++) {
                var val = $scope.skillTypes[i];
                if (val.id == skillTypeId) {
                    return val;
                }
            }
            return $scope.skillTypes[0];
        }

        //init();
    };

    skillsController.$inject = ['$scope', '$log', '$routeParams', 'skillsFactory', 'skillTypeSkills'];
    angular.module('app')
        .controller('SkillsController', skillsController);
}());